package com.tankgame.server;

import com.tankgame.models.BaseTank;
import com.tankgame.panel.GamePanel;
import com.tankgame.utils.Directions;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TankMoveMsg {
  BaseTank tank;

  public TankMoveMsg(BaseTank tank) {
    this.tank = tank;
  }

//  @Override
  public void send(DatagramSocket ds, String ip, int udpPort) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    try {
      dos.writeInt(tank.getId());
      dos.writeInt(tank.getX());
      dos.writeInt(tank.getY());
      dos.writeInt(tank.getDirection().ordinal());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    DatagramPacket dp = new DatagramPacket(baos.toByteArray(), baos.size(), new InetSocketAddress(ip, udpPort));
    try {
      ds.send(dp);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

//  @Override
  public Object parse(DataInputStream dis) {
    try {
      int id = dis.readInt();
//      if (id == this.tank.getId()) return null;
//      System.out.println(id == this.tank.getId());
      int x = dis.readInt();
      int y = dis.readInt();
      int dir = dis.readInt();

      GamePanel gmPanel = GamePanel.GetInstance();
      for (BaseTank tank : gmPanel.getAllTanks()) {
        if (tank.getId() == id) {
          tank.setX(x);
          tank.setY(y);
          tank.setDirection(Directions.values()[dir]);
          break;
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return null;
  }
}
